package com.ganlebao.study.springcloudfeignclient.basic;

import com.ganlebao.study.springcloudfeignclient.basic.acl.GitHubQueryService;
import feign.Response;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

@RestController
@RequestMapping("git-hub")
public class GitHubRepositorySearchController {
    @Autowired
    private GitHubQueryService gitHubQueryService;

    @Autowired
    private ExceptionFeignClient feignClient;

    /**
     * 查询github的仓库信息
     *
     * @param name
     * @return
     */
    @RequestMapping("repository/{name}")
    public String queryRepositoryInfo(@PathVariable("name") String name) {
        if (StringUtils.isBlank(name)) {
            return "仓库名为空";
        }
        Optional<String> result = feignClient.query(() -> gitHubQueryService.searchRepo(name));
        if (result.isPresent()) {
            return result.get();
        } else {
            return "获取内容为空";
        }
    }

    /**
     * 使用gzip压缩访问
     *
     * @param name
     * @return
     */
    @RequestMapping("repository/gzip/{name}")
    public ResponseEntity<byte[]> queryRepositoryInfoGzip(@PathVariable("name") String name) throws IOException {
        if (StringUtils.isBlank(name)) {
            return ResponseEntity.ok("名称不能为空".getBytes(StandardCharsets.UTF_8));
        }
        Optional<ResponseEntity<byte[]>> result = feignClient.query(() ->
                gitHubQueryService.searchRepoUseGzip(name)
        );
        if (result.isPresent()) {
            return result.get();
        } else {
            return ResponseEntity.ok("获取内容为空".getBytes(StandardCharsets.UTF_8));
        }
    }

    /**
     * 查询不存在的页面,查看fallback是否有效
     */
    @RequestMapping("repository/404")
    public String queryRepositoryInfo() {

        Optional<String> result = feignClient.query(() -> gitHubQueryService.notExistsPage("404"));
        if (result.isPresent()) {
            return result.get();
        } else {
            return "获取内容为空";
        }
    }
}
